package cdu.notFound.controller;
import cdu.notFound.model.User;
import cdu.notFound.service.UserService;
import cdu.notFound.service.impl.UserServiceImpl;
import cdu.notFound.utils.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 登录
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	//登录验证，设置session和coookies
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		//获取参数
		String inputEmail = request.getParameter("inputEmail");
		String inputPassword = request.getParameter("inputPassword");
		String autoLogin = request.getParameter("auto_login");
		UserService userService = new UserServiceImpl();
		User user = userService.findByEmail(inputEmail);
		if (user != null) {
			String password = MD5.getMD5(MD5.getMD5(inputPassword));
			//验证密码是否正确
			if (user.getPwd().equals(password)) {
				//判断是否勾选自动登录
				if (autoLogin != null && autoLogin.equals("on")) {
					Cookie cookieE = new Cookie("LOGIN_EMAIL", inputEmail);
					cookieE.setMaxAge(60 * 60 * 24 * 7);
					response.addCookie(cookieE);
				}
				//密码正确登录成功
				HttpSession session = request.getSession();
				session.setAttribute("loginUser",user);
				session.setAttribute("isLogined", true);
				response.sendRedirect("index.jsp");
			} else {
				request.setAttribute("isLoginOk", "false");
				request.getRequestDispatcher("user/login.jsp").forward(
						request, response);
			}
		} else {
			request.setAttribute("isLoginOk", "false");
			request.getRequestDispatcher("user/login.jsp").forward(
					request, response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
